import React, { useState, useEffect, useRef } from 'react';
import { View, Text, Image, Button } from '@tarojs/components';
import Taro from '@tarojs/taro';

import bear3 from '@/assets/imgs/bear3.png';
import bear1 from '@/assets/imgs/bear1.png';
import eye from '@/assets/imgs/eye.png';
import selector from '@/assets/imgs/selector.png';

import bluePaper from '@/assets/imgs/paperTags/bluePaper.png';
import greenPaper from '@/assets/imgs/paperTags/greenPaper.png';
import orangePaper from '@/assets/imgs/paperTags/orangePaper.png';
import pinkPaper from '@/assets/imgs/paperTags/pinkPaper.png';

import {
  sendMessageApi,
  saveMessageApi,
  searchConversitionListApi,
  deleteHistoryConversitionApi,
} from '@/api/handleAiChat.js';

import { searchUserInfoApi } from '@/api/handleUserAccount.js';

import {
  getLatestAppInfoApi,
  downloadAppApi,
} from '@/api/handleAppVersion.js';

import { useUserStore } from '@/store/user.jsx';
import './home.scss';

const Home = () => {
  const paperTags = [bluePaper, greenPaper, orangePaper, pinkPaper];
  const [AIStatus, setAIStatus] = useState('slope');
  const [isChatting, setIsChatting] = useState(false);
  const [isLocalDb, setIsLocalDb] = useState('true');
  const [isLoading, setIsLoading] = useState(false);
  const [currentAnswer, setCurrentAnswer] = useState('');
  const [isDownLoading, setIsDownLoading] = useState(false);
  const [downloadPercent, setDownloadPercent] = useState(0);
  const [sessionList, setSessionList] = useState([]);
  const inputMessage = useRef(null);

  const store = useUserStore()

  useEffect(() => {
    const localDb = Taro.getStorageSync('localDb');
    setIsLocalDb(localDb);
    if (localDb === 'false') {
      searchUserInfoApi().then((userResult) => {
        store.updateUserInfo(userResult)
      });
    }
  }, []);

  const goToPage = (path) => {
    Taro.navigateTo({ url: path });
  };

  const goToMine = () => {
    if (isLocalDb !== 'false') {
      Taro.navigateTo({ url: '/pages/login/login' });
    } else {
      Taro.navigateTo({ url: '/mine' });
    }
  };

  const goToThingsList = () => {
    if (isLocalDb !== 'false') {
      Taro.navigateTo({ url: '/pages/login/login' });
    } else {
      Taro.navigateTo({ url: '/things-list' });
    }
  };

  const changeAIStatus = (param) => {
    setAIStatus(param);
  };

  const searchConversition = async () => {
    setSessionList([]);
    const userInfo = Taro.getStorageSync('userInfo');
    if (userInfo) {
      const roleCode = JSON.parse(userInfo).currentRoleCode;
      const res = await searchConversitionListApi({ roleCode });
      if (res?.length > 0) {
        Taro.setStorageSync('sessionId', res[0].sessionId);
        const newSessionList = res.flatMap((item, index) => [
          {
            id: (res.length - index) * 2 - 1,
            content: item.sessionContent.question,
            type: 'user',
          },
          {
            id: (res.length - index) * 2,
            content: item.sessionContent.answer,
            type: 'AI',
          },
        ]);
        setSessionList(newSessionList.reverse());
      }
    }
  };

  const startSpeak = async () => {
    setIsChatting(true);
    if (sessionList.length === 0 && isLocalDb === 'false') {
      await searchConversition();
    }
  };

  const deleteHistoryConversition = async () => {
    Taro.setStorageSync('sessionId', '');
    const userInfo = Taro.getStorageSync('userInfo');
    if (userInfo) {
      const roleCode = JSON.parse(userInfo).currentRoleCode;
      const res = await deleteHistoryConversitionApi({ roleCode });
      if (res) {
        await searchConversition();
      }
    }
  };

  const collapseSession = () => {
    setIsChatting(false);
  };

  const sendMessage = async () => {
    setCurrentAnswer('');
    const message = inputMessage.current.value;
    if (message) {
      setIsLoading(true);
      const newSessionList = [
        ...sessionList,
        {
          id: sessionList.length + 1,
          type: 'user',
          content: message,
        },
      ];
      setSessionList(newSessionList);

      const params = {
        content: message,
        sessionId: Taro.getStorageSync('sessionId') || '',
      };
      inputMessage.current.value = '';

      const responseStream = await sendMessageApi(params);

      if (responseStream) {
        let analysis = '';
        let conversation_id = Taro.getStorageSync('sessionId') || '';
        const reader = responseStream.getReader();
        const decoder = new TextDecoder();
        let thinkStart = false;

        const read = async () => {
          const { value, done } = await reader.read();
          if (done) {
            const userInfo = Taro.getStorageSync('userInfo');
            const roleCode = JSON.parse(userInfo).currentRoleCode;
            const currentSession = {
              answer: currentAnswer,
              sessionId: Taro.getStorageSync('sessionId'),
              roleCode,
              question: message,
            };
            await saveMessageApi(currentSession);
            setSessionList((prev) => [
              ...prev,
              {
                id: prev.length + 1,
                type: 'AI',
                content: currentAnswer,
              },
            ]);
            setCurrentAnswer('');
            setIsLoading(false);
            return;
          }
          const chunk = decoder.decode(value, { stream: true });
          const lines = chunk.split('\n');
          for (let line of lines) {
            line = line.trim();
            if (!line.startsWith('data:')) continue;
            let dataStr = line.replace(/^data:\s*/, '');
            if (!dataStr) continue;
            let result;
            try {
              result = JSON.parse(dataStr);
            } catch (e) {
              continue;
            }
            if (!conversation_id && result.conversation_id) {
              Taro.setStorageSync('sessionId', result.conversation_id);
              conversation_id = result.conversation_id;
            }
            if (result.event === 'message') {
              let ans = result.answer?.replace(/\n/g, '') || '';
              switch (ans) {
                case '<think>':
                  thinkStart = true;
                  break;
                case '</think>':
                  thinkStart = false;
                  ans = '';
                  break;
              }
              if (thinkStart) {
                analysis += ans;
              } else {
                setCurrentAnswer((prev) => prev + ans);
              }
            }
          }
          read();
        };
        read();
      } else {
        setIsLoading(false);
      }
    } else {
      Taro.showToast({ title: '请输入信息', icon: 'none' });
    }
  };

  const downloadApp = async () => {
    const resInfo = await getLatestAppInfoApi('yrzj');
    const { filePath, version } = resInfo;
    if (filePath) {
      setIsDownLoading(true);
      setDownloadPercent(0);
      Taro.downloadFile({
        url: filePath,
        success: (res) => {
          if (res.statusCode === 200) {
            Taro.saveFile({
              tempFilePath: res.tempFilePath,
              success: (saveRes) => {
                Taro.showToast({
                  title: `下载成功，文件保存在${saveRes.savedFilePath}`,
                  icon: 'success',
                });
              },
            });
          }
        },
        fail: () => {
          Taro.showToast({ title: '下载失败', icon: 'none' });
        },
        onProgressUpdate: (progressRes) => {
          setDownloadPercent(progressRes.progress);
        },
      });
    }
  };

  return (
    <View className="home">
      <View className="operationBar">
        {isLocalDb !== 'false' ? (
          <Text className="login" onClick={() => goToPage('/pages/login/login')}>
            登录
          </Text>
        ) : (
          <View className="role">
            <Image src={selector} alt="" />
            <Text>角色信息</Text>
          </View>
        )}
        <View style={{ color: '#646cff' }} onClick={downloadApp}>
          <Text>下载手机版app</Text>
        </View>
        <View className="deepBtn">
          <Text>开启深度模式</Text>
          <Image src={eye} alt="" />
        </View>
      </View>

      <View className="thingsList" onClick={goToThingsList}>
        <View className='list'>
          {paperTags.map((item, index) => (
            <Image key={index} src={item} alt="" />
          ))}
        </View>
        <View>
          <Text>事项清单</Text>
        </View>
      </View>

      <View className="recentPlan">
        <View className="box">
          <View style={{ marginBottom: 10 }}>
            <Text style={{ fontSize: 20 }}>近期计划</Text>
            <Text
              style={{ fontSize: 16 }}
              onClick={() => goToPage('/to-do-tasks')}
            >
              更多 &gt;&gt;
            </Text>
          </View>
          <View>
            <Text>计划1</Text>
            <Text>
              截止时间 <Text className="endTime">2025.5.1</Text>
            </Text>
            <Text>
              剩余 <Text className="remainTime">1 周</Text>
            </Text>
          </View>
          <View>
            <Text>计划1</Text>
            <Text>
              截止时间 <Text className="endTime">2025.5.1</Text>
            </Text>
            <Text>
              剩余 <Text className="remainTime">1 周</Text>
            </Text>
          </View>
          <View>
            <Text>计划1</Text>
            <Text>
              截止时间 <Text className="endTime">2025.5.1</Text>
            </Text>
            <Text>
              剩余 <Text className="remainTime">1 周</Text>
            </Text>
          </View>
        </View>
      </View>

      <View className="navList">
        <View onClick={goToMine}>
          <Text>我的</Text>
        </View>
        <View onClick={() => goToPage('/to-do-tasks')}>
          <Text>待办</Text>
        </View>
        <View onClick={() => goToPage('/settings')}>
          <Text>设置</Text>
        </View>
      </View>

      <View className="currentStatus">
        <View className="status">
          <Text className="title"> 学习中 </Text>
          <Text className="tips"> 预计2小时后结束 </Text>
          <Text className="immersion">沉浸模式</Text>
        </View>
        <View className="operation">提前终止</View>
      </View>

      <View className='chat-box'>

      <View className="speakBox">
        {AIStatus === 'stand' && (
          <View>
            {!isChatting ? (
              <View className="speak">
                <View>Hello，我是AI小熊，今天你有什么计划吗？</View>
                <View style={{ float: 'right', color: '#e39b80' }} onClick={startSpeak}>
                  开始对话
                </View>
              </View>
            ) : (
              <View className="isChatingBox">
                <View className="header">
                  <Text onClick={collapseSession}>收起</Text>
                  <Text onClick={deleteHistoryConversition}>清空历史会话</Text>
                </View>
                <View className="content">
                  {isLocalDb !== 'false' ? (
                    <View>
                      你还没有登录哦！点击
                      <Text style={{ color: 'red' }} onClick={() => goToPage('/pages/login/login')}>
                        登录
                      </Text>
                      后查看更多吧!
                    </View>
                  ) : (
                    <View className="sessionList">
                      {sessionList.map((item) => (
                        <View
                          key={item.id}
                          className={item.type === 'AI' ? 'AIAgent' : 'user'}
                        >
                          <Text>{item.type === 'AI' ? 'AI小熊' : '我'}</Text>
                          <Text>{item.content}</Text>
                        </View>
                      ))}
                      {currentAnswer && (
                        <View className="AIAgent">
                          <Text>AI小熊</Text>
                          <Text>{currentAnswer}</Text>
                        </View>
                      )}
                    </View>
                  )}
                </View>
                <View className="inputBox">
                  <Input ref={inputMessage} className="input" />
                  {!isLoading ? (
                    <Button className="send" onClick={sendMessage}>
                      发送
                    </Button>
                  ) : (
                    <Button className="send" disabled>
                      会话处理中
                    </Button>
                  )}
                </View>
              </View>
            )}
          </View>
        )}
      </View>

      <View className="AIBear">
        {AIStatus === 'slope' && (
          <Image
            className="slope"
            src={bear3}
            alt=""
            onClick={() => changeAIStatus('stand')}
          />
        )}
        {AIStatus === 'stand' && (
          <Image
            className="stand"
            src={bear1}
            alt=""
            onClick={() => changeAIStatus('slope')}
          />
        )}
      </View>

      </View>

      {isDownLoading && (
        <View className="downloadingLine">
          <Text>下载中......</Text>
          <Progress
            percent={downloadPercent}
            strokeWidth={15}
            activeColor="#5fb3b3"
            backgroundColor="rgba(255,255,255,0.68)"
          />
        </View>
      )}
    </View>
  );
};

export default Home;